<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\controller\adminapi\user;

use app\common\model\addon\Addons;
use app\common\model\platform\Platform;
use app\common\model\user\UserPermission as UserPermissionModel;
use app\common\model\user\User;
use hiduoke\controller\AdminController;
use hiduoke\services\FormBuilder as Form;
use think\App;

/**
 * Notes: 子账号管理
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/8/6 03:52
 */
class UserPermission extends AdminController
{
    protected $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new UserPermissionModel();
    }

    // 获取子账号列表
    public function getList()
    {
        $res = $this->model->getPageList(['$where' => ['plaid' => input('plaid', 0)]]);
        return $this->success($res['count'], $res['data']);
    }

    public function getAddFrom()
    {
        $rule = array();
        //创建表单
        $plaid = input('plaid', 0);
        $form = Form::createForm("/adminapi/user/UserPermission/saveAdd")->setMethod("POST");
        //新增表单
        $rule[] = Form::hidden("plaid", $plaid);
        $rule[] = Form::radio("type", "查询方式", 0)
            ->options([['value' => 0, 'label' => '昵称'], ['value' => 1, 'label' => '用户ID']])
            ->appendControl(0, [Form::dkInput('username', '用户昵称', "", "填写用户昵称，添加后可以对该用户赋予权限")->required()])
            ->appendControl(1, [
                Form::dkInputNumber("uid", "用户UID", "", "填写用户的UID，添加后可以对该用户赋予权限")->required(),
            ]);
        $form->setTitle("新增子账号")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function saveAdd()
    {
        $formData = input('formData', []);
        if ($formData['type'] == 0) {
            $user = (new User())->where(['username' => $formData['username']])->find();
        } else {
            $user = (new User())->where(['uid' => $formData['uid']])->find();
        }
        if (!$user) {
            return $this->error("用户不存在");
        }

        $platform = (new Platform())->where(['plaid' => $formData['plaid']])->find();
        if (!$platform) {
            return $this->error("平台不存在");
        }
        //判断是否已经添加过

        $permission_user = $this->model->where(['plaid' => $formData['plaid'], 'uid' => $user['uid']])->findOrEmpty();
        if (!$permission_user->isEmpty()) {
            return $this->error("当前账号已经存在");
        }

        $permission_user->uid = $user['uid'];
        $permission_user->plaid = $formData['plaid'];
        $permission_user->save();
        return $this->success("添加成功，添加后可以对该用户赋予权限");
    }

    public function deletePermission()
    {
        $id = input('id', 0);
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        if ($row->isEmpty()) {
            return $this->error("数据不存在");
        }
        $row->delete();
        return $this->success("删除成功");
    }

    public function getPermissionForm($id = 0)
    {
        $rule = array();
        //创建表单
        $plaid = input('plaid', 0);
        if (!$plaid) {
            return $this->error("未指定平台");
        }
        $form = Form::createForm("/adminapi/user/UserPermission/savePermission?id=" . $id)->setMethod("POST");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        //新增表单
        $rule[] = Form::tree('platform', '平台权限', $row['platform'] ?? [])
            ->nodeKey('key')
            ->props(['props' => ['label' => 'label']])
            ->data($this->model->getPlatformData($plaid))
            ->defaultExpandAll(true);

        $addonsExplain = (new Addons())->getAddonsByFormDataAddons($row['addons']);
        $rule[] = Form::dkAddonSelect('addons', '应用权限', $row['addons'] ?? [])
            ->addonsExplain($addonsExplain)
            ->prop('platform', true)
            ->appendToBody();

        $form->setTitle("新增子账号")->setRule($rule);
        return $this->success("", Form::getFormData($form), get_addons_config('gs_xsy')['auth'] ?? []);
    }

    public function savePermission($id)
    {
        $formData = getFormData();
        $permission = $this->model->where(['id' => $id])->findOrEmpty();
        $permission->save($formData);
        return $this->success('保存成功', $formData);
    }

    /**
     * 获取平台权限
     * @return \think\response\Json
     */
    public function getPlatformPermission($plaid=0)
    {
        if (!$plaid) {
            return $this->error('平台id不存在');
        }
        $uid = $this->userInfo['uid'];
        $platform = (new Platform())->where(['plaid' => $plaid, 'uid' => $uid])->find();
        if ($platform || $this->userInfo['is_admin']) {
            $auth = ['all'];
        } else {
            $auth = $this->model->where(['plaid' => $plaid, 'uid' => $uid])->field('platform')->findOrEmpty()['platform'] ?? [];
        }
        return $this->success('ok', $auth);
    }

    /**
     * 获取应用权限
     */
    public function getAddonsPermission($plaid)
    {
        $uid = $this->userInfo['uid'];
        $platform = (new Platform())->where(['plaid' => $plaid, 'uid' => $uid])->find();
        if ($platform) {
            $auth = ['all'];
        } else {
            $auth = $this->model->where(['plaid' => $plaid, 'uid' => $uid])->field('addons')->findOrEmpty()['addons'];
        }
        return $this->success('ok', $auth);
    }
}
